<template>
  <header class="bg-dark sticky-top">
    <div class="container">
      <!-- 导航 -->
      <nav class="navbar navbar-expand-lg navbar-dark">
        <!-- logo -->
        <a class="navbar-brand" href="#"></a>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
          <span class="navbar-toggler-icon"></span>
        </button>
        <!-- 功能 -->
        <div class="collapse navbar-collapse" id="navbarSupportedContent">
          <ul class="navbar-nav mr-auto">
            <li class="nav-item ml-3 btn-group-vertical">
              <router-link class="nav-link" to="/index">首页</router-link>
            </li>
            <li class="nav-item ml-3 btn-group-vertical"  v-if="isLogined">
              <router-link class="nav-link position-relative" to="/letter">
                消息
                <span class="badge badge-danger" v-if="totalUnreadCount > 0">{{ totalUnreadCount }}</span>
              </router-link>
            </li>
            <li class="nav-item ml-3 btn-group-vertical" v-if="!isLogined">
              <router-link class="nav-link" to="/register">注册</router-link>
            </li>
            <li class="nav-item ml-3 btn-group-vertical"  v-if="!isLogined">
              <router-link class="nav-link" to="/login">登录</router-link>
            </li>
            <li class="nav-item ml-3 btn-group-vertical dropdown"  v-if="isLogined">
              <a class="nav-link dropdown-toggle" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                <router-link :to="'/profile/' + id">
                  <img :src="headerUrl" class="rounded-circle" style="width:30px;"/>
                </router-link>
              </a>
              <div class="dropdown-menu" aria-labelledby="navbarDropdown">
                <router-link class="dropdown-item text-center" :to="'/profile/' + id">个人主页</router-link>
                <router-link class="dropdown-item text-center" to="/setting">账号设置</router-link>
                <a class="dropdown-item text-center" @click="logout">退出登录</a>
                <div class="dropdown-divider"></div>
                <span class="dropdown-item text-center text-secondary">{{ username }}</span>
              </div>
            </li>
          </ul>
          <!-- 搜索 -->
          <form class="form-inline my-2 my-lg-0">
            <input class="form-control mr-sm-2" type="search" aria-label="Search" v-model="keyword" />
            <button type="button" class="btn btn-outline-light my-2 my-sm-0" @click="toSearch">搜索</button>
          </form>
        </div>
      </nav>
    </div>
  </header>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import User from '@/api/user'
import router from '@/router'
import { useUserStore } from '@/store/modules/user'
import Letter from '@/api/letter'
import Notice from '@/api/notice'
import { useSearchStore } from '@/store/modules/search'
import { removeToken } from '../utils/cookie'

const userStore = useUserStore()

const searchStore = useSearchStore()

const isLogined = ref(false)

const id = ref(0)
const username = ref('')
const headerUrl = ref('')

const totalUnreadCount = ref(0)

const keyword = ref('')

onMounted(async () => {
  getUserInfo()
  if (userStore.username != 'nowcoder') {
    isLogined.value = true
    getTotalUnreadCount()
  }
  if (searchStore.keyword != '') {
    keyword.value = searchStore.keyword
  }
})

const subscribe = userStore.$subscribe(
  (mutation, state) => {
    /*
      * mutation主要包含三个属性值：
      *   events：当前state改变的具体数据，包括改变前的值和改变后的值等等数据
      *   storeId：是当前store的id
      *   type：用于记录这次数据变化是通过什么途径，主要有三个分别是
      *         “direct” ：通过 action 变化的
                ”patch object“ ：通过 $patch 传递对象的方式改变的
                “patch function” ：通过 $patch 传递函数的方式改变的
      *
      * */
    // 在此处监听store中值的变化，当变化为某个值的时候，做一些业务操作
    getUserInfo()
    if (username.value != 'nowcoder') {
      isLogined.value = true
    } else {
      isLogined.value = false
    }
  },
  { detached: false }
)

const getUserInfo = async () => {
    id.value = userStore.id
    username.value = userStore.username
    headerUrl.value = userStore.headerUrl
}

const logout = async () => {
  User.logout().then(() => {
    // 清除登录信息
    userStore.resetDefault()
    // 清除token
    removeToken()
    // 跳转到登录页
    router.push('/login')
  })
}

const getTotalUnreadCount = async () => {
  Letter.getLetterUnreadCount().then(res => {
    Notice.getNoticeUnreadCount().then(res2 => {
      totalUnreadCount.value = res + res2
    })
  })
}

const toSearch = async () => {
  // 跳转到搜索页
  router.push({
    path: '/search',
    query: {
      q: keyword.value
    }
  })
}

</script>
